package com.lkx.util;

import com.lkx.dto.InterfaceVisitorRecordDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

@Slf4j
public class HttpUtils {


    public static void post(RestTemplate restTemplate, String uri, InterfaceVisitorRecordDTO dto) {
        try {
            MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
            params.add("interfaceName", "你好");
            params.add("interfaceUrl", dto.getInterfaceUrl());
            params.add("visitorIp", dto.getVisitorIp());
            params.add("status", dto.getStatus());
            params.add("visitorTime", dto.getVisitorTime());

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
            //将请求头部和参数合成一个请求
            HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity(params.toString(), headers);

            ResponseEntity<String> response = restTemplate.postForEntity(uri, request, String.class);
            log.info("post 请求，参数：{}，返回结果：{}", null, response.getBody());
        } catch (Exception ex) {
            log.error("post 请求出错，参数：{}，返回结果：{}", null, ex.getMessage());
        }
    }


        public static void postForJson(RestTemplate restTemplate,String url, InterfaceVisitorRecordDTO dto) {
            try{
                JSONObject json = new JSONObject();
                json.put("interfaceName", "你好");
                json.put("interfaceUrl", dto.getInterfaceUrl());
                json.put("visitorIp", dto.getVisitorIp());
                json.put("status", dto.getStatus());
                json.put("visitorTime", dto.getVisitorTime());
                //设置Http Header
                HttpHeaders headers = new HttpHeaders();
                //设置请求媒体数据类型
                headers.setContentType(MediaType.APPLICATION_JSON);
                //设置返回媒体数据类型
                headers.add("Accept", MediaType.APPLICATION_JSON.toString());
                HttpEntity<String> formEntity = new HttpEntity<String>(json.toString(), headers);

                restTemplate.postForObject(url, formEntity, String.class);
                log.info("post 请求，参数：{}，返回结果：{}", null, formEntity.getBody());
            } catch (Exception ex) {
                log.error("post 请求出错，参数：{}，返回结果：{}", null, ex.getMessage());
            }
        }

}
